<template>
    <div>
        <el-row class="maina-tab-title">
            <el-col :span="24">
                <div class="flot-left">
                    <!-- <el-button type="primary" plain class="button-put" @click="batchOperation(1)">{{'批量发布'}}</el-button>
                    <el-button type="primary" plain class="button-put" @click="batchOperation(2)">{{'批量回滚'}}</el-button> -->
                </div>
            </el-col>
        </el-row>
        <div>
            <el-table 
            class="table-c"
                v-loading="loading"
                :data="mainTaskList" 
                ref="multipleTable"
                border 
                row-key="sid"
                :tree-props="{children: 'programReleaseLogs', hasChildren: true}"
                :row-class-name='rowClassChange'
                :empty-text="M2('暂无数据')"
                style="width: 100%"
                default-expand-all
                @selection-change="handleSelectionChange" :height='changeMaxHeight()'
                :header-cell-style="{background:'#f5f7fa',color:'#606266',padding:'5px 0px'}"
             >
            <!-- <el-table-column type="selection" width="40" header-align='center'></el-table-column> -->
           <el-table-column prop="id" width="120" label="ID" align="center"></el-table-column>
            <el-table-column prop="releaseId" width="170" label="发布Id" align="center"></el-table-column>
            <el-table-column prop="createOn" width="80" label="创建时间" align="center">
                <template slot-scope="scope">
                    {{formatDate(scope.row.createOn)}}
                </template>
            </el-table-column>
            <el-table-column prop="programInfoId" width="150" label="项目名称" align="center"></el-table-column>
            <el-table-column prop="createName" width="120" label="发布人" align="center"></el-table-column>
            <el-table-column prop="serviceCode" width="120" label="发布到的服务器" align="center"></el-table-column>
            <el-table-column prop="version" width="80" label="服务版本" align="center"></el-table-column>
            <el-table-column prop="programType" width="80" label="项目类型" align="center">
                <template slot-scope="scope">
                    <div v-if="scope.row.programType">
                        {{showTypeName(scope.row.programType,programTypeList)}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="path_Release" width="180" label="发布到的物理地址"></el-table-column>
            <el-table-column prop="path_Backup" width="180" label="备份文件地址"></el-table-column>
            <!-- <el-table-column prop="path_Temp" width="180" label="临时文件地址"></el-table-column> -->
            <el-table-column prop="releaseDescription"  label="发布说明">
                <template slot-scope="scope">
                    <div class="max-lines-3">
                        <el-popover
                            placement="bottom"
                            width="450"
                            trigger="hover"
                            popper-class="whiteWarp"
                            >
                            <div>
                                {{scope.row.releaseDescription}}
                            </div>
                            <div slot="reference" class="whiteWarp">
                                {{scope.row.releaseDescription}}
                            </div>
                        </el-popover>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="type" width="95" label="发布类型" align="center" fixed="right">
                <template slot-scope="scope">
                    <div>
                        <el-popover
                            placement="right"
                            width="180"
                            trigger="hover"
                            v-if="scope.row.auditDescription"
                            >
                            <div>
                                {{scope.row.auditDescription}}
                            </div>
                            <div slot="reference" :style="{color:scope.row.auditStatus == 3 ? '#ff0000bf':''}">
                                <span :style="{color:showColor(scope.row.type)}" :title="(scope.row.auditStatus  == 2 && scope.row.type == 0) || ( scope.row.auditStatus == 3) ? scope.row.auditorName:''">
                                    {{(scope.row.auditStatus  == 0 || scope.row.auditStatus  == 2) ?  showTypeName(scope.row.type,typeList) : showAuditD(scope.row.auditStatus)}}
                                </span>
                            </div>
                        </el-popover>
                        <div v-else :style="{color:scope.row.auditStatus == 3 ? '#ff0000bf':''}">
                            <span :style="{color:showColor(scope.row.type)}" :title="(scope.row.auditStatus  == 2 && scope.row.type == 0) || ( scope.row.auditStatus == 3) ? scope.row.auditorName:''">
                                 {{(scope.row.auditStatus  == 0 || scope.row.auditStatus  == 2) ?  showTypeName(scope.row.type,typeList) : showAuditD(scope.row.auditStatus)}}
                            </span>
                           
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center" fixed="right">
                <template slot-scope="scope">
                    <div v-if="scope.row.parentLevel == 0">
                        <el-button  type="text" v-if="scope.row.toBeReleased && scope.row.toBeReleased.length > 0"  @click="sendServe(scope.row.toBeReleased)">发布  |</el-button>
                        <el-button  type="text" v-if="scope.row.haveReleased && scope.row.haveReleased.length > 0"  @click="rollBack(scope.row.haveReleased)">回滚  |</el-button>
                        <el-button  type="text" v-if="scope.row.toBeReviewed && scope.row.toBeReviewed.length > 0" @click="toExamineList(scope.row.toBeReviewed)">审核</el-button>
                    </div>
                    <div v-else>
                        <span v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 2">
                            <span>
                                <el-button v-if="(scope.row.type === 0 || scope.row.type === 2) && scope.row.hasPermission" type="text"  @click="sendServe(scope.row.id)">发布  |</el-button>
                            </span>
                            <span>
                                <el-button v-if="scope.row.type == 1 && scope.row.hasPermission" type="text"  @click="rollBack(scope.row.id)">回滚  |</el-button>
                            </span>
                        </span>
                        <span v-if="scope.row.auditStatus == 1">
                            <el-button v-if="scope.row.hasAuditPermission " type="text"  @click="toExamineList(scope.row.id)">审核  |</el-button>
                        </span>
                        <span>
                            <el-button  type="text"  @click="openCommonDialog(scope.row.id)">日志</el-button>
                        </span>
                    </div>
                    
                </template>
            </el-table-column>
            </el-table>
        </div>
        <el-pagination
            class="page-box"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[50, 100, 200, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        <!--改动记录-->
        <el-dialog
            title="审核" 
            :visible.sync="dialogVisible" 
            :close-on-click-modal='false'
            width="460px"
            class="dialog-main"
            top="25vh"
            append-to-body
            >
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm" size='mini'>
                <el-form-item label="审核类型：" prop="auditStatus">
                    <el-select v-model="ruleForm.auditStatus"  placeholder="请选择审核类型">
                        <el-option :value="2" label="审核通过"></el-option>
                        <el-option :value="3" label="审核未通过"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="审核说明：" prop="auditDescription">
                    <el-input type="textarea" v-model="ruleForm.auditDescription"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onSubmit()" size="mini">确 定</el-button>
                <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
            </span>
        </el-dialog>
        <commonDialog ref="commonDialog" :titleText="M2('发布历史记录')" width="1000px">
            <el-table :empty-text="M2('暂无数据')" :data="subTableData" style="width: 100%" height="350" border :header-cell-style="{background:'#f5f7fa',color:'#606266'}" >
                <el-table-column  align="center">
                    <template slot="header">
                        {{M2('项目名称')}}
                    </template>
                    <template slot-scope="scope">
                        {{scope.row.programInfoId}}
                    </template>
                </el-table-column>
                <el-table-column  align="center">
                    <template slot="header">
                        {{M2('发布到的服务器')}}
                    </template>
                    <template slot-scope="scope">
                        {{scope.row.serviceCode}}
                    </template>
                </el-table-column>

                <el-table-column align="center">
                    <template slot="header">
                        {{M2('服务版本')}}
                    </template>
                    <template slot-scope="scope">
                        {{scope.row.version}}
                    </template>
                </el-table-column>
                <el-table-column  align="center">
                    <template slot="header">
                        {{M2('发布类型')}}
                    </template>
                    <template slot-scope="scope">
                        <el-popover
                            placement="right"
                            width="180"
                            trigger="hover"
                            v-if="scope.row.auditDescription"
                            >
                            <div>
                                {{scope.row.auditDescription}}
                            </div>
                            <div slot="reference" :style="{color:scope.row.auditStatus == 3 ? '#ff0000bf':''}">
                                <span :style="{color:showColor(scope.row.type)}">
                                    {{(scope.row.auditStatus  == 0 || scope.row.auditStatus  == 2) ?  showTypeName(scope.row.type,typeList) : showAuditD(scope.row.auditStatus)}}
                                </span>
                            </div>
                        </el-popover>
                        <div v-else :style="{color:scope.row.auditStatus == 3 ? '#ff0000bf':''}">
                            <span :style="{color:showColor(scope.row.type)}">
                                {{(scope.row.auditStatus  == 0 || scope.row.auditStatus  == 2) ?  showTypeName(scope.row.type,typeList) : showAuditD(scope.row.auditStatus)}}
                            </span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center">
                    <template slot="header">
                        <div>
                            {{M2('审核人')}}/{{M2('审核时间')}}
                        </div> 
                    </template>
                    <template slot-scope="scope">
                        <div>
                            {{scope.row.auditorName}}
                        </div>
                         <div>
                            {{formatDate(scope.row.auditOn)}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center">
                    <template slot="header">
                        <div>
                            {{M2('创建人')}}/{{M2('创建时间')}}
                        </div> 
                    </template>
                    <template slot-scope="scope">
                       
                        <div>
                            {{scope.row.createName}}
                        </div>
                         <div>
                            {{formatDate(scope.row.createOn)}}
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column width="160" align="center">
                    <template slot="header">
                        {{M2('操作时间')}}
                    </template>
                     <template slot-scope="scope">
                         <div v-if="(scope.row.auditStatus  == 2 && scope.row.type == 0) || ( scope.row.auditStatus == 3)">
                             {{formatDate(scope.row.auditOn)}}
                        </div>
                        <div v-else>
                            {{formatDate(scope.row.createOn)}}
                        </div>
                    </template>
                </el-table-column> -->
            </el-table>
        </commonDialog>
    </div>
</template>
<script>
import debounce from 'lodash.debounce';
import { getProgramReleases,getEmployee,queryProgramReleaseLogsByReleaseId,rollback,release,getProgramReleaseInfoAuth,auditProgramReleases } from '@/api/user.js'
import { formatDate} from '@/utils/tools'
export default {
    components:{
        commonDialog:() => import('@/components/common/commonDialog.vue')
    },
    data(){
        return {
            subTableData:[],
            ruleForm:{},
            rules:{
                auditStatus: [
                    { required: true, message: '请选择审核类型！', trigger: 'blur' }
                ],
            },
            uploadFilterList:{
                search: null, //搜索(供应商、开发ID、sku别名、sku、申请单号)
                serviceCode:null,
                type:0,
                programType:null,
                programInfoId:null, //搜索(供应商、开发ID、sku别名、sku、申请单号)
            },
            dialogVisible:false,
            showTenth:false,
            remarksParam:{},
            total:0,
            currentPage4:0,
            pageSize:50,
            pageNum:1,
            loading:false,
            mainTaskList:[],
            multipleSelection: [],
            getIndex: [],
            // renderDom :false,
            employee:{},
            programTypeList:[
            {
                name:'Web',
                type:'1'
            },
            {
                name:'Service',
                type:'2'
            },
            {
                name:'App',
                type:'3'
            },
        ],
        typeList:[
            {
                name:'待发布',
                type:'0'
            },
            {
                name:'已发布',
                type:'1'
            },
            {
                name:'已回滚',
                type:'2'
            },
            {
                name:'待审核',
                label:'11'
            },
        ],
        }
    },
    props:{
        filterList:{
            default:() => ({})
        }
    },
    created: function() {
        this.mainListList()
        // this.init()
    },
    watch:{
        filterList:{
            handler:function(val){
                this.pageNum = 1
                this.mainListList(val)
                this.uploadFilterList = val
            },
            deep:true
        },
    },
    computed:{
        scrollContainer(){
            return document.querySelector('.el-table__body-wrapper')
        },
        
    },
    methods:{
        showTableName(){
            //(scope.row.auditStatus  == 2 && scope.row.type == 0) || (scope && scope.row && scope.row.auditStatus == 3)
            if(this.subTableData && this.subTableData.length == 0) return false
            if((this.subTableData[0].auditStatus  == 2 && this.subTableData[0].type == 0) || this.subTableData[0].auditStatus == 3){
                return true
            }else {
                return false
            }  
        },
        openCommonDialog(id){
            let param =  {
                id,
            }
            queryProgramReleaseLogsByReleaseId(param).then(res => {
                if(res.code == 200){
                    this.$refs.commonDialog.openCommonDialog()
                    this.subTableData = res.data
                }
            })
        },
        showColor(type){
            if(type == 0) {
                return '#fe9313'
            }else if(type == 1){
                return 'green'
            } else if(type == 2){
                return '#3366cc'
            }else {
                return
            }
        },
        load(tree, treeNode, resolve) {
            let param = {
                releaseId:tree.releaseId
            }
            queryProgramReleaseLogsByReleaseId(param).then(res => {
                res.data.forEach(item => {
                    item.sid = item.id
                })
                getProgramReleaseInfoAuth().then(res1 => {
                    res.data.forEach(item => {
                        res1.data.forEach(item1 => {
                            if(item1.programInfoId == item.programInfoId && item1.version == item.version && item1.serviceCode == item.serviceCode){
                                if(item1.hasPermission) {
                                    item.hasPermission = true
                                }
                                if(item1.hasAuditPermission ) {
                                    item.hasAuditPermission  = true
                                }
                            }
                        })
                    })
                   resolve(res.data)
                })
                
            })
        },
        sendServe(ids) {
            this.$confirm('确定要发布这个配置吗？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let param = typeof ids == 'number' ? [ids] : ids 
                release(param).then(response => {
                    if(response.code == 200 ){
                        this.$message({
                            type: 'success',
                            message: '发布成功！'
                        });
                        this.mainListList()
                    }
                });  
            })
        },
        onSubmit(){
            this.$refs["ruleForm"].validate((valid) => {
                if (valid) {
                    auditProgramReleases(this.ruleForm).then(res => {
                        if(res.code == 200){
                            this.$message({
                                type: 'success',
                                message: '审核成功！'
                            });
                            this.dialogVisible = false;
                            this.mainListList()
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        toExamineList(ids){
            this.ruleForm = {}
            // let param = 
            this.ruleForm.ids = typeof ids == 'number' ? [ids] : ids 
            this.dialogVisible = true
        },
        rollBack(ids) {
            this.$confirm('确定要回滚这个配置吗？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let param = typeof ids == 'number' ? [ids] : ids 
                rollback(param).then(response => {
                    if(response.code == 200){
                        this.$message({
                            type: 'success',
                            message: '回滚成功！'
                        });
                        this.mainListList()
                    }
                })
            }) 
        },
         rowClassChange({row}) {
            if(!row.id) {
                return 'table-row-c'
            }
            else {
                return 'table-row-b'
            }  
        },
        showTypeName(key,list) {
            let name = list.filter(item => {
                return item.type == key
            })
            if(name && name.length > 0){
                 return name[0].name
            }else {
                return ''
            }
        },
        showAuditD(type){
            if(type == 1){
                return '待审核'
            }else if(type == 3) {
                return '审核未通过'
            }
        },
         //点击行触发，选中或不选中复选框
        handleRowClick(row){
            this.$refs.multipleTable.toggleRowSelection(row);
            if(this.getIndex.includes(row.index)) {
                this.getIndex.splice(this.getIndex.findIndex(item => item == row.index),1)
            }else {
                this.getIndex.push(row.index);
            }   
        },

        init(){
            getEmployee().then(res => {
                this.employee = res.data
            })
        },
        mainListList:debounce (function(val){
            if(!val) val = this.uploadFilterList
            this.loading = true
            let param = {
                pageNum:this.pageNum,
                pageSize:this.pageSize,
                serviceCode:val ? val.serviceCode : null,
                type:val ? val.type : null,
                programType:val ? val.programType : null,
                programInfoId:val ? val.programInfoId : null,
                search:val && val.search ? val.search : null,
                // findSubitem:0,
            }
            getProgramReleases(param).then(res => {
                res.data.rows.forEach(el => {
                    el.hasChildren = true
                    el.sid = Math.random()
                    el.programReleaseLogs.forEach(item => {
                        item.sid = item.id
                    })
                    
                });
                getProgramReleaseInfoAuth().then(res1 => {
                    res.data.rows.forEach(item => {
                        item.programReleaseLogs.forEach(item2 => {
                            res1.data.forEach(item1 => {
                                if(item1.programInfoId == item2.programInfoId && item1.version == item2.version && item1.serviceCode == item2.serviceCode){
                                    if(item1.hasPermission) {
                                        item2.hasPermission = true
                                    }
                                    if(item1.hasAuditPermission ) {
                                        item2.hasAuditPermission  = true
                                    }
                                }
                            }) 
                        })
                       
                    })
                    
                    this.mainTaskList = res.data.rows
                    this.total = res.data.records;
                    this.currentPage4 = res.data && res.data.pageNum ? res.data.pageNum : 1
                    this.loading =false
                })
                
            }).catch(res => {
                this.loading = false
            })       
        },500),
        batchOperation(type){

            if(this.multipleSelection.length == 0 || this.multipleSelection.length > 1){
                this.error('请选择一条数据操作！')
                return
            }

            if(type == 1 &&  this.multipleSelection.some(item => item.type != 0)){
                this.error('请选择状态为待发布的数据！')
                return
            }
             if(type == 2 &&  this.multipleSelection.some(item => item.type != 1)){
                this.error('请选择状态为已发布的数据！')
                return
            }
            if(this.multipleSelection.some(item => item.releaseId != this.multipleSelection[0].releaseId)){
                this.error('请选择相同发布id的数据！')
                return
            }

            let name 
            if(type == 1){
                name = '发布'
            }else [
                name = '回滚'
            ]
            this.$confirm((`是否确认${name}该${this.multipleSelection.length}条数据？`), { 
                confirmButtonText: this.M2('确定'),
                cancelButtonText: this.M2('取消'),
                type: 'warning'
                }).then(() => {
                let param = {
                    ids:this.multipleSelection.map(item => item.id).toString()
                }
                let fn = null
                if(type == 1){
                    fn = release(param)
                }else [
                    fn = rollback(param)
                ]
                fn.then((res) => {
                    if(res.code == 200){
                        this.success('操作成功！')
                    }
                this.mainListList()
            }).catch(() => {
                return
            });
        }).catch(() => {
            return
        })
        },
        changeMaxHeight(){
            let nHeight = 0
            if(document.querySelector('.nav-card')){
                if(navigator.userAgent.indexOf('WebKit') > -1) {
                    nHeight = 60
                }else {
                    nHeight = 60
                }
                return window.innerHeight - document.querySelector('.nav-card').offsetHeight + 10 - nHeight  + 'px' 
            }
                return window.innerHeight - 255 + 'px' 
        },
        //时间格式修改
        formatDate(row) {
            if(row){
                return formatDate(row);
            }else {
                return ''
            }
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.mainListList(this.uploadFilterList)
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.mainListList(this.uploadFilterList)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        success(msg) {
            this.$message({
                showClose: true,
                message:this.M2(msg),
                offset:220,
                duration: 2000,
                type: 'success'
            });
        },
        warning(msg) {
            this.$message({
                showClose: true,
                message: this.M2(msg),
                offset:220,
                type: 'warning'
            });
        },
        error(msg) {
            this.$message({
                showClose: true,
                message: msg,
                offset:220,
                type: 'error'
            });
        },
    }
}
</script>
<style scoped lang="scss">
::v-deep.table-c{
    td {
        padding: 2px;
    }
    .cell{
        padding: 0px !important;
    }
}
.border-b{
    border-bottom: 1px solid #e6ebf5;
    min-height: 70px;
}
.dropdown-class.el-dropdown-menu {
    width: 100px;
}
::v-deep.dialog-main {
    .el-dialog__header {
        padding: 10px 20px 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ccc;
    }
    .el-dialog__body {
        padding: 10px 20px;
    }
}
.page-box{
    position: fixed;
    bottom: 10px;
    right: 30px;
}
.button-put{
    padding: 5px 10px;
    font-size: 12px;
}
.maina-tab-title{
    top: -2px;
    .flot-left{
        float: left;
    }
    .order-position{
        margin-left: 10px;
    }
}
.el-table td {
    padding: 0px !important;
}
</style>
<style  lang="scss" >
.table-row-b {
    background-color: #f1f1f1 !important;
}
.table-row-c {
    background-color: #fff !important;
    font-weight: bold;
    .cell {
        color: #606266;
    }
}
</style>